/**
 * Created by ZhangChaosheng on 2018/3/28 0006.
 */
$(function(){

    var before=0,after = 0,peopleBg=$("#peopleBg"),top;
    var height = peopleBg.height();
    $(window).scroll(function(){
        after = $(document).scrollTop();
        if( after > 100 ){
            $('body').removeClass('headCommon').addClass('headFixed');
            $("#to-top").show();
        }
        if( after < before && after < 50 ){
            $('body').removeClass('headFixed').addClass("headCommon");
            $("#to-top").hide();
        }
        peopleBg.css({
            transform:'translate(0,'+after*0.2+'px)'
        });
        before = after;


    });

    //返回顶部
    $("#to-top").click(function() {
        $("html,body").animate({scrollTop:0}, 500);
    });

    //搜索
    $("#searchBtn").on("click",function(){
        if( $(this).hasClass("active") ){
            $("#search").hide();
            $("body").removeClass("hidden");
            $(this).removeClass("active");

        }else{
            $("#search").fadeIn();
            $("body").addClass("hidden");
            $(this).addClass("active");
            $("#scrollList").slimScroll({
                height: $("#search-list").height(),
                scrollTo: '0px'
            });
        }
    })

});


/***
 * 头部下拉框
 * **/
function showLanguage(btn,list){
    var timer = null;
    $(btn).hover(function() {
        $(".head-menu").hide();
        $(btn).addClass("active");
        $(list).show();
        clearTimeout(timer);
    }, function() {
        timer = setTimeout(function(){
            clearTimeout(timer);
            $(btn).removeClass("active");
            $(list).hide();
        },500)
    });
    $(list).hover(function() {
        $(list).show();
        $(btn).addClass("active");
        clearTimeout(timer);
    }, function() {
        timer = setTimeout(function(){
            clearTimeout(timer);
            $(btn).removeClass("active");
            $(list).hide();
        },500)
    });
}


/***
 * banner切换
 * **/
function bannerSlider(obj,page){
    var items = $(obj).find(".item");
    var currentIndex = 0;
    var timer = null;
    var time = 3000;
    var pageItems;

    function itemChange(n){
        items.fadeOut();
        items.eq(n).show();
        if( page && items.length > 1 ){
			pageItems = $(".pagination .bullet");
            pageItems.removeClass("active");
            pageItems.eq(n).addClass("active");
        }
    }

    function createPage(num){
        var pageCont = $("<div></div>");
        pageCont.attr("class","pagination");
        for( var i=0; i<num; i++ ){
            var bulletCont = $("<span></span>");
            bulletCont.attr("class","bullet");
            bulletCont.appendTo(pageCont);
        }
        pageCont.appendTo(obj);
    }

    function autoPlay(){
        timer = setInterval(function(){
            currentIndex++;
            if( currentIndex === items.length ){
                currentIndex = 0;
            }
            itemChange(currentIndex);
        },time)
    }

    function init(){
        if( items.length > 1 ){
            autoPlay();
            if(page){
                createPage(items.length);
            }
        }
        itemChange(currentIndex);
    }
    init();

}


//计数器
function inputNumber(obj,max,callback){

    var minus = $(obj).find(".minus-btn");
    var plus = $(obj).find(".plus-btn");
    var input = $(obj).find(".number");
    var initNum = 1;

    addDisabled();

    plus.on("click",function(){
        initNum = input.val();
        initNum++;
        if( initNum > max ){
            initNum = max;
        }
        input.val(initNum);
        addDisabled();
    });

    minus.on("click",function(){
        initNum = input.val();
        initNum--;
        if( initNum < 1 ){
            initNum = 1;
        }
        input.val(initNum);
        addDisabled();
    });

    input.keyup(function(){
        if(!/^[+]{0,1}(\d+)$/.test($(this).val())){
            $(this).val(initNum)
        }
        if( parseInt($(this).val()) === 0 ){
            $(this).val(1);
        }
        if( parseInt($(this).val()) > max ){
            $(this).val(max);
        }
        addDisabled();
    });

    function addDisabled(){
        var val = parseInt(input.val());
        if( callback && callback instanceof Function ){
            callback(val);
        }
        if( val === 1 ){
            minus.addClass("disabled");
        }else if( val === max ){
            plus.addClass("disabled");
        }else{
            minus.removeClass("disabled");
            plus.removeClass("disabled");
        }
    }

}

/***
 * tab选项卡
 * ****/
function initTab(obj,scrollObj,scrollHeight){
    var aItem = $(obj).find(".tab-title a");
    var tabItem = $(obj).find(".tab-item");
    var current = 0;
    aItem.each(function(index){
        $(this).on('click',function(){
            current = index;
            changeTab(current);
            return false;
        })
    });
    function changeTab(n){
        aItem.removeClass("active").eq(n).addClass("active");
        tabItem.hide();
        tabItem.eq(n).show();
        if( scrollObj && scrollHeight ){
            $(scrollObj).slimScroll({
                height: scrollHeight,
                scrollTo: '0px'
            });
        }
    }
    changeTab(current);
}


/**
 * 倒计时
 * @param {String} futureDate yyyy-MM-dd hh:mm:ss  2018-3-10 23:23:23
 * @param {String} obj
 */
function countdown(futureDate,obj){

    var leftTime = new Date(futureDate) - new Date();
    var timer = null;
    var day,hour,minute,second;
    if ( leftTime >= 0 ) {
        day = Math.floor(leftTime/1000/60/60/24);
        hour = Math.floor(leftTime/1000/60/60%24);
        minute = Math.floor(leftTime/1000/60%60);
        second = Math.floor(leftTime/1000%60);
        if( day > 0 ){
            $(obj).html(day+"<span>天</span> "+addZero(hour)+" : "+addZero(minute)+" : "+addZero(second))
        }else{
            $(obj).html(addZero(hour)+" : "+addZero(minute)+" : "+addZero(second))
        }
        timer = setInterval(function(){
            return countdown(futureDate,obj)
        },1000);
    }else{
        $(obj).html("00 : 00 : 00");
        clearInterval(timer);
    }

    function addZero(i){
        if(i < 10){
            i = "0" + i;
        }
        return i;
    }

}

/**
 * 本地图片上传查看
 * @params {String}  fileObj
 * @params {String}  imgShowObj
 * **/
function uploadImage(fileObj,imgShowObj,errorObj){

    fileObj.change(function() {
        var filePath = $(this).val();
        var imgHtml = '';
        var objUrl = '';
        for(var i = 0; i < this.files.length; i++) {
            objUrl = getObjectURL(this.files[i]);
            var extStart = filePath.lastIndexOf(".");
            var ext = filePath.substring(extStart, filePath.length).toUpperCase();
            if(ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
                fileObj.val('');
                $(errorObj).html('<span class="error">图片限于bmp,png,gif,jpeg,jpg格式</span>');
                return false;
            } else if( this.files[i].size > 1024*1024 ){
                fileObj.val('');
                $(errorObj).html('<span class="error">上传图片超过1M</span>');
                return false;
            }else {
                $(errorObj).html('上传图片格式为jpg/png，上传图片大小每张不能超过1M');
                imgHtml = "<img class='upload-img' src='" + objUrl + "' />";
                $(imgShowObj).append(imgHtml);
            }
        }
        return true;
    });

    function getObjectURL(file) {
        var url = null;
        if(window.createObjectURL != undefined) {
            url = window.createObjectURL(file);
        } else if(window.URL != undefined) {
            url = window.URL.createObjectURL(file);
        } else if(window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }



}

/***
 * 登录页面的背景
 * ***/
function loginBgInit(){

    var starNum = 200;
    var canvas = document.getElementById("canvas");
    var canvasWidth = $(window).width();
    var canvasHeight = $(".login").outerHeight();
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    var context = canvas.getContext("2d");
    var stars = [];
    var speed = 0.01;
    function starsInit(){
        context.fillStyle = '#090723';
        context.fillRect(0,0,canvasWidth,canvasHeight);
        addArc();
        for(var i =0; i<starNum ; i++){
            var star = stars[i];
            if( star.a > 0.6 ){
                star.a -= speed;
            }else if( star.a < 0.05 ){
                star.a += speed;
            }
            star.x += star.vx;
            if(star.x >= canvasWidth){
                star.x = 0;
            }else if(star.x < 0){
                star.x = canvasWidth;
            }
            star.y += star.vy;
            if(star.y >= canvasHeight){
                star.y = 0;
            }else if(star.y<0){
                star.y = canvasHeight;
            }
            context.beginPath();
            var bg = context.createRadialGradient(star.x, star.y, 0, star.x, star.y, star.r);
            bg.addColorStop(0,'rgba(255,255,255,'+star.a+')');
            bg.addColorStop(1,'rgba(255,255,255,0)');
            context.fillStyle  = bg;
            context.arc(star.x,star.y, star.r, 0, Math.PI*2, true);
            context.fill();
            context.closePath();
        }
    }

    function addStars(){
        for( var i=0; i<starNum; i++ ){
            stars.push({
                x : Math.round(Math.random()*canvasWidth),
                y : Math.round(Math.random()*canvasHeight),
                r : Math.random()*3,
                a : Math.random()*0.5,
                vx : Math.random()*0.2 - 0.1,
                vy : Math.random()*0.2 - 0.1
            })
        }
    }

    function addArc(){
        context.beginPath();
        context.fillStyle = "#52102c";
        context.arc(canvasWidth - 300,-100, 200, 0, Math.PI*2, true);
        context.fill();
        context.closePath();

        context.beginPath();
        context.fillStyle = "rgba(33,24,31,0.6)";
        context.arc(canvasWidth - 150,300, 45, 0, Math.PI*2, true);
        context.fill();
        context.closePath();

        context.beginPath();
        context.fillStyle = "rgba(9,12,45,0.6)";
        context.arc(canvasWidth - 350,400, 25, 0, Math.PI*2, true);
        context.fill();
        context.closePath();
    }

    addStars();
    starsInit();
    setInterval(starsInit,10);

}


function myToast(text,status){
    var backgroundColor = "#888";
    if( status === "error" ){
        backgroundColor = "#d9534f";
    }
    if( status === "warning" ){
        backgroundColor = "#f0ad4e";
    }
    if( status === "info" ){
        backgroundColor = "#5bc0de";
    }
    if( status === "success" ){
        backgroundColor = "#5cb85c";
    }
    Toastify({
        text: text,
        duration: 3000,
        gravity: "top",
        positionLeft: false,
        close: true,
        backgroundColor: backgroundColor
    }).showToast();
}


/**
 * 获取验证码
 * ***/
function getCode(btn,time){
    var timeStorage = time;
    var timer = null;
    $(btn).attr("disabled","disabled");
    $(btn).html(time+"s可再次获取");
    timer = setInterval(function(){
        time--;
        if( time >= 0 ){
            showNotice(time);
        }else{
            clearInterval(timer);
            time = timeStorage;
            $(btn).removeAttr("disabled");
            showNotice();
        }
    },1000);
    function showNotice(time){
        if( time ){
            $(btn).html(time+"s可再次获取");
        }else{
            $(btn).html("获取验证码")
        }
    }
}

